package easeui.widget.chatrow;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.Ext;
import com.github.postsanf.yinian.bean.YNHistory;
import com.github.postsanf.yinian.bean.YNMember;
import com.github.postsanf.yinian.bean.YNUser;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.StringUtils;
import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.util.DateUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;

import java.util.Date;
import java.util.List;

import easeui.adapter.EaseMessageAdapter;
import easeui.widget.EaseChatMessageHistoryList2;

public abstract class EaseChatHistoryRow2 extends LinearLayout {
    protected static final String TAG = EaseChatHistoryRow2.class.getSimpleName();

    protected LayoutInflater inflater;
    protected Context context;
    protected BaseAdapter adapter;
    protected YNHistory message;
    protected int position;

    protected TextView timeStampView;
    protected ImageView userAvatarView;
    protected View bubbleLayout;
    protected TextView usernickView;

    protected TextView percentageView;
    protected ProgressBar progressBar;
    protected ImageView statusView;
    protected Activity activity;

    protected TextView ackedView;
    protected TextView deliveredView;

    protected EMCallBack messageSendCallback;
    protected EMCallBack messageReceiveCallback;

    protected EaseChatMessageHistoryList2.MessageListItemClickListener itemClickListener;
    protected BaseApplication application;

    public EaseChatHistoryRow2(Context context, YNHistory message, int position, BaseAdapter adapter) {
        super(context);
        this.context = context;
        this.activity = (Activity) context;
        this.message = message;
        this.position = position;
        this.adapter = adapter;
        inflater = LayoutInflater.from(context);
        application = (BaseApplication) activity.getApplication();
        initView();
    }

    private void initView() {
        onInflateView();
        timeStampView = (TextView) findViewById(R.id.timestamp);
        userAvatarView = (ImageView) findViewById(R.id.iv_userhead);
        bubbleLayout = findViewById(R.id.bubble);
        usernickView = (TextView) findViewById(R.id.tv_userid);
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        statusView = (ImageView) findViewById(R.id.msg_status);
        ackedView = (TextView) findViewById(R.id.tv_ack);
        deliveredView = (TextView) findViewById(R.id.tv_delivered);

        onFindViewById();
    }

    /**
     * set property according message and postion
     *
     * @param message
     * @param position
     */
    public void setUpView(YNHistory message, int position,
                          EaseChatMessageHistoryList2.MessageListItemClickListener itemClickListener) {
        this.message = message;
        this.position = position;
        this.itemClickListener = itemClickListener;
        setUpBaseView();
        onSetUpView();
        setClickListener();
    }


    private String type;
    private String msg;
    private int direction;
    private String accountName;
    private String img;

    private void setUpBaseView() {
        direction = message.getFrom().equals(String.valueOf(application.getCurID())) ? 0 : 1;
        String extStr = message.getPayload().getExt();
        if (!StringUtils.isEmpty(extStr) && !extStr.equals("{}")) {
            Ext ext = new Gson().fromJson(extStr.replaceAll("\\\\", ""), Ext.class);
            if (ext != null) {
                if (ext.getImg() != null && !StringUtils.isEmpty(ext.getImg())) {
                    img = ext.getImg();
                }
                if (ext.getAccountName() != null && !StringUtils.isEmpty(ext.getAccountName())) {
                    accountName = ext.getAccountName();
                }
                if (ext.getType() != null && !StringUtils.isEmpty(ext.getType())) {
                    type = String.valueOf(ext.getType());
                }
                if (ext.getIntoQuitMessage() != null && !StringUtils.isEmpty(ext.getIntoQuitMessage())) {
                    msg = ext.getIntoQuitMessage();
                }
            }
        }
        TextView timestamp = (TextView) findViewById(R.id.timestamp);
        if (!StringUtils.isEmpty(type) && type.equals("66")) {
            timestamp.setVisibility(View.VISIBLE);
            userAvatarView.setVisibility(View.GONE);
            if (!StringUtils.isEmpty(msg)) {
                timestamp.setText(msg);
            }
        } else {
            timestamp.setVisibility(View.GONE);
            userAvatarView.setVisibility(View.VISIBLE);
            if (timestamp != null) {
                if (position == 0) {
                    timestamp.setText(DateUtils.getTimestampString(new Date(message.getTimestamp())));
                    timestamp.setVisibility(View.VISIBLE);
                } else {
                    // show time stamp if interval with last message is > 30 seconds
                    YNHistory prevMessage = (YNHistory) adapter.getItem(position - 1);
                    if (prevMessage != null && DateUtils.isCloseEnough(message.getTimestamp(), prevMessage.getTimestamp())) {
                        timestamp.setVisibility(View.GONE);
                    } else {
                        timestamp.setText(DateUtils.getTimestampString(new Date(message.getTimestamp())));
                        timestamp.setVisibility(View.VISIBLE);
                    }
                }
            }
            //set nickname and avatar
            if (direction == 0) {
                YNUser ynUser = application.getCurUser();
                ImageLoader.getInstance().displayImage(ynUser.getUpic(), new ImageViewAware(userAvatarView, false), ImageOptHelper.getAvatarOptions());
//            EaseUserUtils.setUserAvatar(context, EMClient.getInstance().getCurrentUser(), userAvatarView);
            } else {
                try {
                    ImageLoader.getInstance().displayImage(img, new ImageViewAware(userAvatarView, false), ImageOptHelper.getAvatarOptions());
                    List<YNMember> ynMemberList = application.getMemberList();
                    String notename = null;
                    for (int i = 0; i < ynMemberList.size(); i++) {
                        if (ynMemberList.get(i).getUser().getUnickname().equals(accountName)) {
                            notename = ynMemberList.get(i).getUser().getNoteName();
                        }
                    }
                    if (!StringUtils.isEmpty(notename)) {
                        usernickView.setText(notename);
                    } else {
                        usernickView.setText(accountName);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
//            EaseUserUtils.setUserAvatar(context, message.getFrom(), userAvatarView);
//            EaseUserUtils.setUserNick(message.getFrom(), usernickView);
            }

            if (adapter instanceof EaseMessageAdapter) {
                if (((EaseMessageAdapter) adapter).isShowAvatar())
                    userAvatarView.setVisibility(View.VISIBLE);
                else
                    userAvatarView.setVisibility(View.GONE);
                if (usernickView != null) {
                    if (((EaseMessageAdapter) adapter).isShowUserNick())
                        usernickView.setVisibility(View.VISIBLE);
                    else
                        usernickView.setVisibility(View.GONE);
                }
                if (direction == 0) {
                    if (((EaseMessageAdapter) adapter).getMyBubbleBg() != null) {
                        bubbleLayout.setBackgroundDrawable(((EaseMessageAdapter) adapter).getMyBubbleBg());
                    }
                } else if (direction == 1) {
                    if (((EaseMessageAdapter) adapter).getOtherBuddleBg() != null) {
                        bubbleLayout.setBackgroundDrawable(((EaseMessageAdapter) adapter).getOtherBuddleBg());
                    }
                }
            }
        }
    }

    /**
     * set callback for sending message
     */
    protected void setMessageSendCallback() {
        if (messageSendCallback == null) {
            messageSendCallback = new EMCallBack() {

                @Override
                public void onSuccess() {
                    updateView();
                }

                @Override
                public void onProgress(final int progress, String status) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (percentageView != null)
                                percentageView.setText(progress + "%");

                        }
                    });
                }

                @Override
                public void onError(int code, String error) {
                    updateView();
                }
            };
        }
    }

    /**
     * set callback for receiving message
     */
    protected void setMessageReceiveCallback() {
        if (messageReceiveCallback == null) {
            messageReceiveCallback = new EMCallBack() {

                @Override
                public void onSuccess() {
                    updateView();
                }

                @Override
                public void onProgress(final int progress, String status) {
                    activity.runOnUiThread(new Runnable() {
                        public void run() {
                            if (percentageView != null) {
                                percentageView.setText(progress + "%");
                            }
                        }
                    });
                }

                @Override
                public void onError(int code, String error) {
                    updateView();
                }
            };
        }
    }


    private void setClickListener() {
        if (bubbleLayout != null) {
            bubbleLayout.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (itemClickListener != null) {
                        if (!itemClickListener.onBubbleClick(message)) {
                            // if listener return false, we call default handling
                            Log.i("xjs","huanx条目点击");
                            onBubbleClick();
                        }
                    }
                }
            });

//            bubbleLayout.setOnLongClickListener(new OnLongClickListener() {
//
//                @Override
//                public boolean onLongClick(View v) {
//                    if (itemClickListener != null) {
//                        itemClickListener.onBubbleLongClick(message);
//                    }
//                    return true;
//                }
//            });
        }

        if (statusView != null) {
            statusView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (itemClickListener != null) {
                        itemClickListener.onResendClick(message);
                    }
                }
            });
        }

        if (userAvatarView != null) {
//            userAvatarView.setOnClickListener(new OnClickListener() {
//
//                @Override
//                public void onClick(View v) {
//                    if (itemClickListener != null) {
//                        if (message.direct() == Direct.SEND) {
//                            itemClickListener.onUserAvatarClick(EMClient.getInstance().getCurrentUser());
//                        } else {
//                            itemClickListener.onUserAvatarClick(message.getFrom());
//                        }
//                    }
//                }
//            });
//            userAvatarView.setOnLongClickListener(new OnLongClickListener() {
//
//                @Override
//                public boolean onLongClick(View v) {
//                    if (itemClickListener != null) {
//                        if (message.direct() == Direct.SEND) {
//                            itemClickListener.onUserAvatarLongClick(EMClient.getInstance().getCurrentUser());
//                        } else {
//                            itemClickListener.onUserAvatarLongClick(message.getFrom());
//                        }
//                        return true;
//                    }
//                    return false;
//                }
//            });
        }
    }


    protected void updateView() {
        activity.runOnUiThread(new Runnable() {
            public void run() {
                onUpdateView();
            }
        });

    }

    protected abstract void onInflateView();

    /**
     * find view by id
     */
    protected abstract void onFindViewById();

    /**
     * refresh list view when message status change
     */
    protected abstract void onUpdateView();

    /**
     * setup view
     */
    protected abstract void onSetUpView();

    /**
     * on bubble clicked
     */
    protected abstract void onBubbleClick();

}
